import 'package:core_package/ui/widget/my_asset_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/model/device_info_model.dart';
import 'package:flutter_app_unionad/model/pay_rule_model.dart';
import 'package:flutter_app_unionad/model/share_pic_model.dart';
import 'package:flutter_app_unionad/request/facility_request.dart';
import 'package:flutter_app_unionad/request/promotion_request.dart';
import 'package:flutter_app_unionad/ui/basice/base_navigation_widget.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/my_facility/widget/recharge_finish_ad_widget.dart';
import 'package:flutter_app_unionad/ui/my_facility/widget/select_pay_type_widget.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart';

//充值
class RechargePage extends StatefulWidget {
  static const String routeName = "/rechargePage";
  final DeviceInfoModel? infoModel;

  const RechargePage({Key? key, this.infoModel}) : super(key: key);

  @override
  _RechargePageState createState() => _RechargePageState();
}

class _RechargePageState extends State<RechargePage> {
  int index = 0;
  List<PayRuleModel>? dataSource;
  int? hot;
  SharePicModel? item;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    thirdPayListen();
    // if (widget.infoModel.channelId.stringIsNotEmpty || widget.infoModel.userType.stringIsNotEmpty) {
    FacilityRequest.payRuleList(devID: UserCacheUil.getString(Configuration.deviceId)).then((value) {
      if (value != null) {
        dataSource = value;
        index = dataSource!.length - 1;
        if (mounted) setState(() {});
      }
    });
    // }
    PromotionRequest.getShareInfo(type: 3).then((value) {
      if (mounted) item = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return BaseNavigationWidget(
      title: "充值",
      needScrollView: dataSource == null || dataSource!.length == 0 ? false : true,
      child: buildContent(),
    );
  }

  Widget buildContent() {
    if (dataSource == null) {
      return ProgressDialog.showFirstLoading();
    }
    if (dataSource!.length == 0) {
      return EmptyWidget();
    }
    print("index ---${dataSource![index]}");
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.px),
      ),
      padding: EdgeInsets.symmetric(horizontal: 25.px, vertical: 50.px),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.infoModel == null
                ? "选择天数"
                : widget.infoModel!.userType == '01' || widget.infoModel!.userType == '02'
                    ? "选择天数"
                    : '选择流量',
            style: TextStyle(
              color: MyColors.formHex("#272727FF"),
              fontSize: MyFont.font16,
              fontWeight: MyFontWeight.bold,
            ),
          ),
          MySizeBox(height: 40),
        ]
          ..addAll(buildList())
          ..add(MySizeBox(height: 40))
          ..add(Center(
            child: MyButton(
              title: "支付(${dataSource![index].price})",
              onTap: () {
                //
                rechargeOnTop();
              },
            ),
          )),
      ),
    );
  }

  List<Widget> buildList() {
    return List.generate(dataSource!.length, (index) {
      return buildItem(index);
    });
  }

  Widget buildItem(int index) {
    PayRuleModel item = dataSource![index];

    Widget child = Text(
      "天",
      style: TextStyle(
        color: MyColors.formHex("#272727FF"),
        fontSize: MyFont.font13,
        fontWeight: MyFontWeight.regular,
      ),
    );
    if (item.billingMode == 1) {
      child = Text(
        "流量(送${item.giftDays}流量)",
        style: TextStyle(
          color: MyColors.formHex("#272727FF"),
          fontSize: MyFont.font13,
          fontWeight: MyFontWeight.regular,
        ),
      );
    } else if (item.giftDays != null && item.giftDays != '' && item.giftDays != '0') {
      child = Text(
        "天(送${item.giftDays}天)",
        style: TextStyle(
          color: MyColors.formHex("#272727FF"),
          fontSize: MyFont.font13,
          fontWeight: MyFontWeight.regular,
        ),
      );
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        setState(() {
          this.index = index;
        });
      },
      child: Stack(
        children: [
          Container(
            margin: EdgeInsets.only(bottom: 10.px),
            width: SizeFill.screenWidth! - 60,
            height: 50.px,
            decoration: BoxDecoration(
                image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(MyAssetsImages.setAssetsImagesPath(index == this.index ? "icon_bg_2" : "icon_bg_3")),
            )),
            alignment: Alignment.center,
            child: Stack(
              children: [
                Container(
                  width: SizeFill.screenWidth! - 60,
                  padding: EdgeInsets.symmetric(horizontal: 15.px),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          MyAssetImage(index == this.index ? "icon_select" : "icon_unselect",
                              width: 12.px, height: 12.px),
                          MySizeBox(width: 15.px),
                          Container(
                            width: 45.px,
                            child: Text(
                              item.day.toString(),
                              style: TextStyle(
                                color: MyColors.formHex("#272727FF"),
                                fontSize: MyFont.font20,
                                fontWeight: MyFontWeight.bold,
                              ),
                            ),
                          ),
                          child,
                        ],
                      ),
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: item.price.toString(),
                          style: TextStyle(
                            color: MyColors.formHex("#272727FF"),
                            fontSize: MyFont.font20,
                            fontWeight: MyFontWeight.bold,
                          ),
                        ),
                        WidgetSpan(child: MySizeBox(width: 5)),
                        TextSpan(
                          text: '元',
                          style: TextStyle(
                            color: MyColors.formHex("#272727FF"),
                            fontSize: MyFont.font13,
                            fontWeight: MyFontWeight.regular,
                          ),
                        ),
                      ])),
                      Text(
                        "单价：${item.unitPrice}元/天",
                        style: TextStyle(
                          color: MyColors.formHex("#272727FF"),
                          fontSize: MyFont.font13,
                          fontWeight: MyFontWeight.regular,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          if (index == dataSource!.length - 1)
            Positioned(
                right: 5,
                top: 5,
                child: Image.asset(
                  MyAssetsImages.setAssetsImagesPath('icon_recommend.png'),
                  width: 30.px,
                  height: 30.px,
                ))
        ],
      ),
    );
  }

  //立即充值
  void rechargeOnTop() {
    ShowBottomAlertDialog.showBottomDialog(
      context,
      builder: (ctx) {
        return SelectPayTypeWidget(
          weChatPayOnTop: () {
            //
            PayRuleModel item = dataSource![index];
            ProgressDialog.showPayFirstLoading(context);
            FacilityRequest.weChatAppPay(
              amount: num.parse(item.price ?? '0'),
              devId: UserCacheUil.getString(Configuration.deviceId),
              openId: UserCacheUil.getString(Configuration.openid),
              payRuleId: item.id.toString(),
            ).then((value) {
              ProgressDialog.dismiss(context);

              if (value == null) {
              } else {
                //微信支付
                payThird(value, 0);
              }
            });
          },
          alipayPayOnTop: () {
            //

            PayRuleModel item = dataSource![index];
            ProgressDialog.showPayFirstLoading(context);
            FacilityRequest.aliAppPay(
              amount: num.parse(item.price ?? '0'),
              devId: UserCacheUil.getString(Configuration.deviceId),
              openId: UserCacheUil.getString(Configuration.openid),
              payRuleId: item.id.toString(),
            ).then((value) {
              ProgressDialog.dismiss(context);

              if (value == null) {
              } else {
                //阿里支付
                payThird(value, 1);
              }
            });
          },
        );
      },
      height: 168.px + SizeFill.statusHeight!,
    );
  }

  String? record;

  void payThird(dynamic orderModel, int type) async {
    if (type == 0) {
      //微信支付

      record = orderModel['payInfo']['id'];
      String s = orderModel['appPayResponse']['timeStamp'];
      final future = await payWithWeChat(
        appId: orderModel['appPayResponse']['appId'],
        partnerId: orderModel['appPayResponse']['partnerid'],
        prepayId: orderModel['appPayResponse']['prepayid'],
        packageValue: orderModel['appPayResponse']['package'],
        nonceStr: orderModel['appPayResponse']['nonceStr'],
        timeStamp: int.parse(s),
        sign: orderModel['appPayResponse']['paySign'],
      );
      print(future);
      if (future == null || !future) {
        ShowToastWidget.showToast(msg: "支付失败");
      }
    } else if (type == 1) {
      //支付宝支付

      print("支付宝支付 ---${tobias.isAliPayInstalled()}");
      tobias.aliPay(orderModel).then((value) {
        print(value["resultStatus"]);
        if (value["resultStatus"] == "9000") {
          // ShowToastWidget.showToast(msg: '支付成功');
          RechargeFinishAdWidget.show(
            context,
            orderID: record ?? '',
            item: item,
          );
        } else {
          ShowToastWidget.showToast(msg: value["memo"]);
        }
      });
    }
  }

//微信支付监听
  void thirdPayListen() async {
    weChatResponseEventHandler.listen((res) {
      if (res is WeChatPaymentResponse) {
        print(res.errCode);
        if (res.errCode == 0) {
          //支付成功
          // ShowToastWidget.showToast(msg: '支付成功');
          RechargeFinishAdWidget.show(
            context,
            orderID: record ?? '',
            item: item,
          );
        } else {
          ShowToastWidget.showToast(msg: res.errStr == null || res.errStr!.length == 0 ? "支付失败" : res.errStr!);
        }
      }
    });
//    _pay = _alipay.payResp().listen(_listenPay);
  }
}
